import struct
from collections import OrderedDict

from ..base import BaseParser


class GetInstrumentInfo(BaseParser):

    def setParams(self, start, count=100):
        pkg = bytearray.fromhex('01 04 48 67 00 01 08 00 08 00 f5 23')
        pkg.extend(struct.pack('<IH', start, count))

        self.send_pkg = pkg

    def parseResponse(self, body_buf):
        start, count = struct.unpack('<IH', body_buf[:6])

        pos = 6
        result = []

        for i in range(count):
            (category, market, unused_bytes, code_raw, name_raw, desc_raw) = \
                struct.unpack('<BB3s9s17s9s', body_buf[pos: pos + 40])

            code = code_raw.decode('gbk', 'ignore')
            name = name_raw.decode('gbk', 'ignore')
            desc = desc_raw.decode('gbk', 'ignore')

            one = OrderedDict(
                [
                    ('category', category),
                    ('market', market),
                    ('code', code.rstrip('\x00')),
                    ('name', name.rstrip('\x00')),
                    ('desc', desc.rstrip('\x00')),
                ]
            )

            pos += 64
            result.append(one)

        return result
